/**
 * 系统管理  用户管理
 */
<template>
  <div>
    <!-- 搜索筛选 -->
    <el-form ref="searchFrom" :inline="true" :model="formInline" class="user-search">
      <el-form-item prop="username" label="搜索：">
        <el-input v-model="formInline.username" size="small" placeholder="输入用户名称" />
      </el-form-item>
      <el-form-item prop="phone" label="">
        <el-input v-model="formInline.phone" size="small" placeholder="输入手机号码" />
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">
          搜索
        </el-button>
        <el-button size="small" type="primary" icon="el-icon-delete" @click="resetForm('searchFrom')">
          重置
        </el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit(true)">
          添加
        </el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table
      v-loading="loading"
      size="small"
      :data="listData"
      highlight-current-row
      border
      element-loading-text="拼命加载中"
      style="width: 100%"
    >
      <el-table-column align="center" prop="userId" label="ID" width="60" />
      <el-table-column align="center" label="头像" width="100">
        <template slot-scope="scope">
          <el-row class="demo-avatar demo-basic">
            <div class="block">
              <el-avatar :size="50" :src="scope.row.avatar" />
            </div>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名称" width="200" />
      <el-table-column prop="phone" label="手机号码" width="200" />
      <el-table-column prop="updateTime" label="修改时间" width="100" />
      <el-table-column label="部门名称" width="200">
        <template slot-scope="scope">
          <div v-for="item in options" :key="item.deptId">
            <span v-if="scope.row.deptId === item.deptId">
              {{ item.name }}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(false, scope.$index, scope.row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="roleDelete(scope.$index, scope.row)">
            删除
          </el-button>
          <el-button size="mini" type="success" @click="resetpwd(scope.$index, scope.row)">
            重置密码
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination :child-msg="pageparm" @callFather="callFather" />
    <!-- 编辑界面 -->
    <el-dialog
      v-if="editFormVisible"
      :title="title"
      :visible.sync="editFormVisible"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form ref="editForm" label-width="120px" :model="editForm" :rules="rules">
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            action="/upload/setFileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="editForm.username" size="small" auto-complete="off" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="editForm.phone" size="small" auto-complete="off" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item v-if="show" label="登录密码" prop="password">
          <el-input v-model="editForm.password" size="small" auto-complete="off" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <treeselect
            v-model="editForm.deptId"
            :options="menuOptions"
            :normalizer="normalizer"
            :show-count="true"
            placeholder="选择所属部门"
          />
        </el-form-item>
        <el-form-item label="用户角色" prop="roleIds">
          <el-select v-model="editForm.roleIds" multiple placeholder="请选择角色">
            <el-option
              v-for="role in listRoleData"
              :key="role.roleId"
              :label="role.roleName"
              :value="role.roleId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">
          取消
        </el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { userList, userSave, updateUser, deleteUser, userPwd, getRolelist, deptList, getDeptlist } from '@/api/userMG'
import Pagination from '@/components/Pagination'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export function validatePhone (rule, value, callback) {
  const reg = /^[1][3-9][0-9]{9}$/
  if (value === '' || value === undefined || value === null) {
    callback()
  } else if ((!reg.test(value)) && value !== '') {
    callback(new Error('请输入正确的电话号码'))
  } else {
    callback()
  }
}
export default {
  // 注册组件
  components: {
    Pagination,
    Treeselect
  },
  data () {
    return {
      clearable: false, // 清空搜索框
      nshow: true, // switch开启
      fshow: false, // switch关闭
      loading: false, // 是显示加载
      show: '', // 判断是否显示密码框
      listData: [], // 用户列表数据
      listRoleData: [], // 角色列表数据
      editFormVisible: false, // 控制编辑页面显示与隐藏
      disabled: false, // 是否禁用下拉框
      title: '',
      // data: '',
      options: [], // 下拉框数据
      menuOptions: [], // 部门列表
      // 添加编辑
      editForm: {
        userId: '',
        username: '',
        phone: '',
        deptId: '',
        avatar: '',
        password: '',
        roleIds: []
      },
      // 重置密码
      resetpsd: {
        userId: ''
        // token: localStorage.getItem('logintoken')
      },
      // 删除用户
      seletedata: {
        userId: ''
        // token: localStorage.getItem('logintoken')
      },
      // rules表单验证
      rules: {
        avatar: [{ required: true, message: '请选择图片', trigger: 'blur' }],
        username: [{ required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 20 个字符', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' },
          { min: 11, max: 11, validator: validatePhone, trigger: 'blur' }],
        password: [{ required: true, message: '请输入登录密码', trigger: 'blur' },
          { min: 6, max: 255, message: '长度在 6 到 255 个字符', trigger: 'blur' }],
        deptId: [{ required: true, message: '请选择部门', trigger: 'blur' }],
        roleIds: [{ required: true, message: '请选择角色', trigger: 'blur' }]
      },
      formInline: {
        pageNum: 1,
        pageSize: 10,
        username: '',
        phone: ''
      },
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      }
    }
  },
  /**
   * 创建完毕
   */
  created () {
    this.getdata(this.formInline)
    // 获取部门层级列表
    this.getDeptdata()
    // 获取部门列表
    this.deptlist()
    // 获取角色列表
    this.getRoledata()
  },
  methods: {
    // 获取公司列表
    getdata (parameter) {
      this.loading = true
      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      userList(parameter)
        .then((res) => {
          this.loading = false
          // eslint-disable-next-line eqeqeq
          if (res.code != 0) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            this.listData = res.data.list
            // 分页赋值
            this.pageparm.currentPage = this.formInline.pageNum
            this.pageparm.pageSize = this.formInline.pageSize
            this.pageparm.total = res.data.total
          }
        })
        // eslint-disable-next-line handle-callback-err
        .catch((err) => {
          this.loading = false
          this.$message.error('菜单加载失败，请稍后再试！')
        })
    },
    // 获取角色列表
    getRoledata (parameter) {
      this.loading = true
      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      getRolelist(parameter)
        .then((res) => {
          this.loading = false
          // eslint-disable-next-line eqeqeq
          if (res.code != 0) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            this.listRoleData = res.data
          }
        })
        // eslint-disable-next-line handle-callback-err
        .catch((err) => {
          this.loading = false
          this.$message.error('角色加载失败，请稍后再试！')
        })
    },
    // 获取部门层级列表
    getDeptdata (parameter) {
      this.loading = true
      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      deptList(parameter)
        .then((res) => {
          this.loading = false
          // eslint-disable-next-line eqeqeq
          if (res.code != 0) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            this.menuOptions = []
            const dept = { deptId: 0, name: '总公司', children: [] }
            dept.children = res.data
            this.menuOptions.push(dept)
          }
        })
        // eslint-disable-next-line handle-callback-err
        .catch((err) => {
          this.loading = false
          this.$message.error('部门加载失败，请稍后再试！')
        })
    },
    // 获取部门列表
    deptlist () {
      getDeptlist()
        .then((res) => {
          // eslint-disable-next-line eqeqeq
          if (res.code != 0) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            this.options = res.data
          }
        })
        // eslint-disable-next-line handle-callback-err
        .catch((err) => {
          this.$message.error('获取部门列表失败，请稍后再试！')
        })
    },
    // 搜索事件
    search () {
      this.formInline.pageNum = 1
      this.getdata(this.formInline)
    },
    // 重置按钮
    resetForm (formName) {
      // 重置要看 <el-form-item>的组件元素上是否指定了字段名。指定了才会重置生效
      this.$refs[formName].resetFields()
      this.formInline.pageNum = 1
      this.getdata(this.formInline)
    },
    // 显示编辑界面
    handleEdit (isShow, index, row) {
      // 判断是否显示密码输入框
      this.show = isShow
      this.editFormVisible = true
      if (row !== undefined && row !== 'undefined') {
        this.title = '编辑'
        this.disabled = false
        this.editForm.userId = row.userId
        this.editForm.avatar = row.avatar
        this.editForm.username = row.username
        this.editForm.phone = row.phone
        this.editForm.deptId = row.deptId
        this.editForm.roleIds = row.roleIds
      } else {
        this.title = '添加'
        this.disabled = false
        this.editForm.userId = ''
        this.editForm.avatar = ''
        this.editForm.username = ''
        this.editForm.phone = ''
        this.editForm.deptId = 0
        this.editForm.password = ''
        this.editForm.roleIds = ''
      }
    },
    // 编辑、增加页面保存方法
    submitForm (editData) {
      this.$refs[editData].validate((valid) => {
        if (valid) {
          if (this.title === '添加') {
            userSave(this.editForm)
              .then((res) => {
                this.editFormVisible = false
                this.loading = false
                if (res.code === 0) {
                  this.getdata(this.formInline)
                  this.$message({
                    type: 'success',
                    message: '用户保存成功！'
                  })
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              // eslint-disable-next-line handle-callback-err
              .catch((err) => {
                this.editFormVisible = false
                this.loading = false
                this.$message.error('用户保存失败，请稍后再试！')
              })
          }
          if (this.title === '编辑') {
            updateUser(this.editForm)
              .then((res) => {
                this.editFormVisible = false
                this.loading = false
                if (res.code === 0) {
                  this.getdata(this.formInline)
                  this.$message({
                    type: 'success',
                    message: '用户保存成功！'
                  })
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              // eslint-disable-next-line handle-callback-err
              .catch((err) => {
                this.editFormVisible = false
                this.loading = false
                this.$message.error('用户保存失败，请稍后再试！')
              })
          }
        } else {
          return false
        }
      })
    },
    // 删除用户
    roleDelete (index, row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // eslint-disable-next-line no-undef
          deleteUser(row.roleId)
            .then((res) => {
              if (res.code === 0) {
                this.getdata(this.formInline)
                this.$message({
                  type: 'success',
                  message: '用户已删除!'
                })
                this.getdata(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            // eslint-disable-next-line handle-callback-err
            .catch((err) => {
              this.loading = false
              this.$message.error('用户删除失败，请稍后再试！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 分页插件事件
    callFather (parm) {
      this.formInline.pageNum = parm.currentPage
      this.formInline.pageSize = parm.pageSize
      this.getdata(this.formInline)
    },
    // 关闭编辑、增加弹出框、并清空数据
    closeDialog () {
      this.editFormVisible = false
      // this.$refs[formName].resetFields()
      // this.$nextTick(() => {
      //   this.$refs.editForm.resetFields()
      // })
    },
    // 重置密码
    resetpwd (index, row) {
      this.resetpsd.userId = row.userId
      this.$confirm('确定要重置密码吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // eslint-disable-next-line no-undef
          userPwd(this.resetpsd)
            .then((res) => {
              if (res.success) {
                this.$message({
                  type: 'success',
                  message: '重置密码成功！'
                })
                this.getdata(this.formInline)
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            // eslint-disable-next-line handle-callback-err
            .catch((err) => {
              this.loading = false
              this.$message.error('重置密码失败，请稍后再试！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消重置密码！'
          })
        })
    },
    // 上传图片
    handleAvatarSuccess (res, file) {
      // this.editForm.avatar = URL.createObjectURL(file.raw)
      // 主要配合后台映射路径
      this.editForm.avatar = '/images' + res.path
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return (isJPG || isPNG) && isLt2M
    },
    /** 转换菜单数据结构 */
    normalizer (node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.deptId,
        label: node.name,
        children: node.children
      }
    }
  }
}
</script>
<style lang="scss">
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 18px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>
